<template>
  <div class="__common-layout-pageTabs">
    <Breadcrumb/>
    <div style="float:right;marginTop:8px" v-if="UPDATE_NEWS!=''">
      <img  src="@assets/alert.png" alt="" >
      {{UPDATE_NEWS}}
    </div>
<!--    <div>-->
<!--    <a-tabs v-model="activeKey" hide-add type="editable-card" @edit="(targetKey, action) => remove(targetKey)" @change="change">-->
<!--        <a-tab-pane v-for="pane in openedPageRouters" :key="pane.fullPath" :tab="$t(pane.meta.title)" :closable="true">-->
<!--        </a-tab-pane>-->
<!--    </a-tabs>-->
      <!-- <div class="__tabs" id="pageTabContainer"> -->
<!--        <span><a-icon type="left"/></span>-->
    <draggable v-model="openedPageRouters"  chosenClass="chosen" :forceFallback="true" ghostClass="tab-drag-ghost" group="people"
               animation="1000" @start="onStart" @end="onEnd" :touchStartThreshold="10" :delay="10" :fallbackTolerance="10">
      <transition-group class="__tabs" id="pageTabContainer">
        <div
          class="__tab-item"
          v-for="(item,index) in openedPageRouters"
          :class="{
            '__is-active': item.fullPath === $route.fullPath || item.fullPath === $route.path + '/' || item.fullPath + '/' === $route.path,
          }"
          :key="item.key || item.fullPath"
          @click="onClick(item)"
          @contextmenu.prevent="showContextMenu($event, item)"
        >
          <a-tooltip :title="getPageTitle(item)" placement="top" :ref="'tab-'+index" :getPopupContainer="$commonFun.getPopupContainer">
            {{ $t(item.meta.title) }}
            <span @click.stop="remove(item.fullPath)"
                  @contextmenu.prevent.stop=""
                  :style="openedPageRouters.length <= 1 ? 'width:0;' : ''">
              <i class="iconfont icon-guanbi el-icon-close" style=""/>
            </span>
          </a-tooltip>
        </div>
      </transition-group>
    </draggable> 
  <!-- </div> -->
<!--    </div>-->
    <div v-show="contextMenuVisible">
      <ul
        :style="{ left: contextMenuLeft + 'px', top: contextMenuTop + 'px' }"
        class="__contextmenu"
      >
        <li>
          <a-button type="link" @click.rl="reload()" size="small">
            重新加载
          </a-button>
        </li>
        <li>
          <a-button
            type="link"
            @click="closeOtherLeft"
            :disabled="false"
            size="small"
          >关闭左边
          </a-button>
        </li>
        <li>
          <a-button
            type="link"
            @click="closeOtherRight"
            :disabled="false"
            size="small"
          >关闭右边
          </a-button>
        </li>
        <li>
          <a-button type="link" @click="closeOther" size="small">关闭其他
          </a-button>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
  import Breadcrumb from '@/components/tools/Breadcrumb.vue'
  import draggable from 'vuedraggable'
  import { minxinDrawerUse } from '@/utils/mixin'
  import Drawer from '@/components/Drawer/drawer.js'
  import { mapState, mapActions } from 'vuex'
  export default {
    components:{Breadcrumb,draggable},
    props: {
      keepAliveComponentInstance: {}, //keep-alive控件实例对象
      blankRouteName: {
        type: String,
        default: "blank",
      }, //空白路由的name值
      //新页签追加位置：last - 追加到最后，current - 追加到当前页签后面
      newTabAppendTo: {
        type: String,
        default: "current",
      }
    },
    mixins: [minxinDrawerUse],
    computed:{
       ...mapState({
        UPDATE_NEWS: state => state.sysAnnounce.UPDATE_NEWS,
      })
    },
    data() {
      let data = {
        drag:false,
        activeKey: '',
        contextMenuVisible: false, //右键菜单是否显示
        contextMenuLeft: 0, //右键菜单显示位置
        contextMenuTop: 0, //右键菜单显示位置
        contextMenuTargetPageRoute: null, //右键所指向的菜单路由
        openedPageRouters: [], //已打开的路由页面
        compToDestroy: []
      };
      if(sessionStorage.openedPageRouters){
        try {
          data.openedPageRouters = JSON.parse(sessionStorage.openedPageRouters);
        } catch (e) {
          console.error(`Invalid sessionStorage.openedPageRouters,${sessionStorage.openedPageRouters}`);
          delete sessionStorage.openedPageRouters;
        }
      }
      return data;
    },
    watch: {
      //当路由变更时，执行打开页面的方法
      $route: {
        handler(v, o) {
          // 抽屉默认是页签级别，不需要收起
          // this.removeRightDrawer()
          this.openPage(v, o);
        },
        immediate: true,
      },
      openedPageRouters(newV, oldV){
        sessionStorage.openedPageRouters = JSON.stringify([...newV].map(value => {
          let {matched, ...reduced} = value;
          return reduced;
        }));
      }
    },
    mounted() {
      this.queryUpdateNews()
      //添加点击关闭右键菜单
      window.addEventListener("click", this.closeContextMenu);
    },
    destroyed() {
      window.removeEventListener("click", this.closeContextMenu);
    },
    methods: {
        ...mapActions(['queryUpdateNews']),
        //开始拖拽事件
      onStart(e){
        // this.$refs['tab-' + e.oldIndex][0].visible=false;
        // this.openedPageRouters[e.oldIndex].tooltip=false;
        this.drag=true;
      },
      //拖拽结束事件
       onEnd(e) {
         // this.$refs['tab-' + e.oldIndex][0].visible=true;
         // this.openedPageRouters[e.oldIndex].tooltip=true;
         this.drag=false;
      },
      change(key) {
        let route = this.openedPageRouters.find(
          (item) => item.fullPath === key
        );
        this.onClick(route);
      },
      //打开页面
      openPage(route, oldRoute) {
        if (route.name === this.blankRouteName) {
          return;
        }
        // if(route.path.length > 1 && route.path[route.path.length - 1] === '/'){
        //   route.path = route.path.substring(0, route.path.length -1);
        // }
        let exist = this.openedPageRouters.find(
          (item) => item.fullPath === route.fullPath || item.fullPath + '/' === route.fullPath || item.fullPath === route.fullPath + "/"
        );
        let index;
        let container = document.getElementById("pageTabContainer");
        if (!exist) {
          let openedPageRoute = this.openedPageRouters.find(
            (item) => item.path === route.path || item.path + '/' === route.path || item.path === route.path + "/"
          );
          this.activeKey = route.fullPath;
          //判断页面是否支持不同参数多开页面功能，如果不支持且已存在path值一样的页面路由，那就替换它
          let tabData = {...route, key : route.meta.canMultipleOpen ? route.fullPath : route.path}
          if (!route.meta.canMultipleOpen && openedPageRoute != null) {
            this.delRouteCache(openedPageRoute.fullPath);
            this.openedPageRouters.splice(this.openedPageRouters.indexOf(openedPageRoute), 1, tabData);
            return;
          } else {
            if (this.newTabAppendTo === 'last') {
              this.openedPageRouters.push(tabData);
              //滚动条到最右边
              this.$nextTick(()=>{
                if(container){
                  container.scrollLeft = container.scrollWidth
                }
              });
              return;
            } else {
              let currentIndex = !oldRoute ? -1 : this.openedPageRouters.findIndex(
                (item) => item.fullPath === oldRoute.fullPath
              );
              index = currentIndex < 0 ? this.openedPageRouters.length : currentIndex + 1;
              this.openedPageRouters.splice(index, 0, tabData);
            }
          }
        }else{
          index = this.openedPageRouters.indexOf(exist);
        }
        //滚动条定位
        function scroll() {
          container = document.getElementById("pageTabContainer");
          let node = container.childNodes[index];
          let left = node.offsetLeft;
          if (left > container.scrollLeft + container.clientWidth - node.clientWidth) {
            //右边不显示
            container.scrollLeft = left + node.clientWidth;
            // container.scrollLeft += left - 0.5 * container.clientWidth + node.clientWidth;
          }else if (left < container.scrollLeft) {
            //左边不显示
            container.scrollLeft = left;
          }
        }
        this.$nextTick(() => {
          if (!container) {
            //部分元素未渲染完，宽度不准确，延时执行
            setTimeout(scroll, 100);
          } else {
            scroll();
          }
        })
      },
      //点击页面标签卡时
      onClick(route) {
        if (route.fullPath !== this.$route.fullPath) {
          this.$router.push(route.fullPath);
        }
      },
      //关闭页面标签时
      remove(key, jump = true) {
        let route = this.openedPageRouters.find(
          (item) => item.fullPath === key
        );
        let index = this.openedPageRouters.indexOf(route);
        if (this.openedPageRouters.length === 1) {
          return;
        }
        this.delPageRoute(route);
        if (jump && route.fullPath === this.$route.fullPath) {
          //删除页面后，跳转到上一页面
          this.$router.replace(
            this.openedPageRouters[index === 0 ? 0 : index - 1]
          );
        }
      },
      //右键显示菜单
      showContextMenu(e, route) {
        this.contextMenuTargetPageRoute = route;
        this.contextMenuLeft = e.pageX;
        this.contextMenuTop = e.pageY;
        if (document.body.clientWidth - e.pageX < 108) {
          this.contextMenuLeft -= 108;
        }
        this.contextMenuVisible = true;
      },
      //隐藏右键菜单
      closeContextMenu() {
        this.contextMenuVisible = false;
        this.contextMenuTargetPageRoute = null;
      },
      //重载页面
      reload() {
        var vm  = this;
        this.delRouteCache(this.contextMenuTargetPageRoute.fullPath);
        if (this.contextMenuTargetPageRoute.fullPath === this.$route.fullPath) {
          this.$router.replace({ name: this.blankRouteName }).then(() => {
            this.$router.replace(vm.contextMenuTargetPageRoute);
          });
        }
      },
      //关闭其他页面
      closeOther() {
        for (let i = 0; i < this.openedPageRouters.length; i++) {
          let r = this.openedPageRouters[i];
          if (r !== this.contextMenuTargetPageRoute) {
            this.delPageRoute(r);
            i--;
          }
        }
        if (this.contextMenuTargetPageRoute.fullPath !== this.$route.fullPath) {
          this.$router.replace(this.contextMenuTargetPageRoute);
        }
      },
      //根据路径获取索引
      getPageRouteIndex(fullPath) {
        for (let i = 0; i < this.openedPageRouters.length; i++) {
          if (this.openedPageRouters[i].fullPath === fullPath) {
            return i;
          }
        }
      },
      //关闭左边页面
      closeOtherLeft() {
        let index = this.openedPageRouters.indexOf(
          this.contextMenuTargetPageRoute
        );
        let currentIndex = this.getPageRouteIndex(this.$route.fullPath);
        if (index > currentIndex) {
          this.$router.replace(this.contextMenuTargetPageRoute);
        }
        for (let i = 0; i < index; i++) {
          let r = this.openedPageRouters[i];
          this.delPageRoute(r);
          i--;
          index--;
        }
      },
      //关闭右边页面
      closeOtherRight() {
        let index = this.openedPageRouters.indexOf(
          this.contextMenuTargetPageRoute
        );
        let currentIndex = this.getPageRouteIndex(this.$route.fullPath);
        for (let i = index + 1; i < this.openedPageRouters.length; i++) {
          let r = this.openedPageRouters[i];
          this.delPageRoute(r);
          i--;
        }
        if (index < currentIndex) {
          this.$router.replace(this.contextMenuTargetPageRoute);
        }
      },
      //删除页面
      delPageRoute(route) {
        let routeIndex = this.openedPageRouters.indexOf(route);
        if (routeIndex >= 0) {
          this.openedPageRouters.splice(routeIndex, 1);
        }
        this.delRouteCache(route.fullPath);
        //关闭页签时，销毁页签抽屉。如果不在此处关闭，需要minxin全局destroy钩子进行销毁，但组件并没有path 信息。
        Drawer.close(route.fullPath);
      },
      //删除页面缓存
      delRouteCache(key) {
        if (!this.keepAliveComponentInstance) {
          return;
        }
        let cache = this.keepAliveComponentInstance.cache;
        let keys = this.keepAliveComponentInstance.keys;
        for (let i = 0; i < keys.length; i++) {
          if (keys[i] === key) {
            if (cache[key] != null) {
              // this.compToDestroy.push(key);
              cache[key].componentInstance.$destroy();
              keys.splice(i, 1);
              delete cache[key];
            }
            break;
          }
        }
      },
      getPageTitle(item) {
        if (!item.meta.breadList) {
          return this.$t(item.meta.title);
        }
        return item.meta.breadList.map(item => this.$t(item)).join("/");
      }
    },
  };
</script>
<style lang="less" scoped>
  .__common-layout-pageTabs {
    ::v-deep .ant-breadcrumb{
      display: inline-block;
    }
    .tab-drag-ghost {
      .ant-tooltip{
        display:none;
      }
      /*background: red!important;*/
    }
    .ant-tabs.ant-tabs-card .ant-tabs-card-bar {
      margin: 0 0 0px 0;
      .ant-tabs-nav-container, .ant-tabs-tab {
        /*height: 30px;*/
        /*line-height: 28px;*/
      }
    }

    .__contextmenu {
      // width: 100px;
      margin: 0;
      border: 1px solid #e4e7ed;
      background: #fff;
      z-index: 3000;
      position: fixed;
      /*position: absolute;*/
      list-style-type: none;
      padding: 5px 0;
      border-radius: 4px;
      font-size: 14px;
      color: #333;
      box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.1);
      li {
        margin: 0;
        padding: 0 5px;
        &:hover {
          background: #f2f2f2;
          cursor: pointer;
        }
        button {
          color: #2c3e50;
        }
        .ant-btn{
          height: 24px;
        }
      }
    }

    @c-tab-border-color: #dcdfe6;
    position: relative;
    &::before {
      content: "";
      border-bottom: 1px solid @c-tab-border-color;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      /*height: 100%;*/
    }
    .__tabs {
      display: flex;
      overflow-y: auto;
      .__tab-item {
        user-select: none;
        z-index: 2;
        white-space: nowrap;
        padding: 0 16px;
        height:35px;
        line-height: 33px;
        /*padding: 8px 6px 8px 18px;*/
        font-size: 13px;
        border: 1px solid @c-tab-border-color;
        display: inline-flex;
        /*border-left: none;*/
        /*border-bottom: 0px;*/
        /*line-height: 14px;*/
        cursor: pointer;
        transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1),
        padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);

        /*border: 1px solid rgba(0, 0, 0, 0.1);*/
        border-radius: 4px 4px 0 0;
        margin-right: 2px;
        background: #f5f5f5;
        /*background: #fafafa;*/
        &:first-child {
          border-left: 1px solid @c-tab-border-color;
          border-top-left-radius: 2px;
          margin-left: 10px;
        }
        &:last-child {
          border-top-right-radius: 2px;
          margin-right: 10px;
        }
        &:not(.__is-active):hover {
          color: #4388A6;
          .el-icon-close {
            /*width: 12px;*/
            margin-right: 0px;
          }
        }
        &.__is-active {
          padding-right: 12px;
          border-bottom: 1px solid #fff;
          color: #4388A6;
          background: white;
          .el-icon-close {
            /*width: 12px;*/
            /*margin-right: 0px;*/
            margin-left: 12px;
          }
        }
        .el-icon-close {
          /*width: 0px;*/
          height: 15px;
          /*overflow: hidden;*/
          /*border-radius: 50%;*/
          font-size: 15px;
          /*margin-right: 12px;*/
          transform-origin: 100% 50%;
          transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
          cursor:pointer;
          margin-left:2px;
          /*vertical-align: text-top;*/
          &:hover {
            background-color: #c0c4cc;
            color: #fff;
          }
        }
      }
    }
  }
</style>